package com.learn.eduadboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.learn.eduadboot.mapper.PromotionAdMapper;
import com.learn.eduadboot.service.PromotionAdService;
import com.learn.eduadboot.util.RedisUtils;
import com.learn.eduapi.entity.ad.PromotionAd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class PromotionAdServiceImpl implements PromotionAdService {
    @Autowired
    private PromotionAdMapper promotionAdMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public List<PromotionAd> getAdsBySpaceId(Integer sid) {
        System.out.println("====先查Redis====");
        List<PromotionAd> list = (List<PromotionAd>)redisUtils.get("adList");
                if (list == null) {
                    //去数据库
                    System.out.println("====MySql数据库====");
                    list = promotionAdMapper.getAdsBySpaceId(sid);
                    // 把从数据库查询的集合放在redis内存中
                    redisUtils.set("adList", list, 10, TimeUnit.SECONDS);
                }
        return list;
    }

    @Override
    public int deleteAd(Integer id) {
        int i = promotionAdMapper.deleteById(id);
        //清楚Redis缓存
        if (redisUtils.get("adList")!=null){
            redisUtils.remove("adList");
        }
        return i;
    }

    @Override
    public int updateAd(PromotionAd promotionAd, Wrapper<PromotionAd> wrapper) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = sdf.format(date);
        promotionAd.setUpdate_time(dateString);
        //清楚Redis缓存
        if (redisUtils.get("adList")!=null){
            redisUtils.remove("adList");
        }
        return promotionAdMapper.update(promotionAd,wrapper);
    }

    @Override
    public PromotionAd selectByName(String name) {
        return promotionAdMapper.selectByName(name);
    }

    @Override
    public int addAd(PromotionAd promotionAd) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = sdf.format(date);
        promotionAd.setCreate_time(dateString);
        promotionAd.setUpdate_time(dateString);
        //清楚Redis缓存
        if (redisUtils.get("adList")!=null){
            redisUtils.remove("adList");
        }
        return promotionAdMapper.insert(promotionAd);
    }

    @Override
    public List<PromotionAd> getAllPromotionAd(String find, Integer page, Integer size) {
        return promotionAdMapper.getAllPromotionAd(find, page, size);
    }
}
